"use strict";

/**
 * 
 * @desc   千分位分隔符
 * @param  {Number} num 
 * @param  {Number} decimal 
 * @return {NumStr}
 */
function toThousands(num, decimal) {
  if (!num && num !== 0) {
    return;
  }

  num = num + '';
  var reg = /\d{1,3}(?=(\d{3})+$)/g;
  var intNum = '';
  var decimalNum = '';

  if (num.indexOf('.') > -1) {
    intNum = num.substring(0, num.indexOf('.'));
    decimalNum = num.substring(num.indexOf('.') + 1, num.length);
    var cimal = parseFloat(num).toFixed(decimal);
    var rest = cimal.substring(cimal.indexOf('.') + 1, cimal.length);
    var dec = decimal ? rest : '';
    return (intNum + '').replace(reg, '$&,') + '.' + (decimal ? dec : decimalNum);
  } else {
    var _cimal = parseInt(10).toFixed(decimal);

    var _rest = _cimal.substring(_cimal.indexOf('.') + 1, _cimal.length);

    var _dec = decimal ? '.' + _rest : '';

    return (num + '').replace(reg, '$&,') + _dec;
  }
}

module.exports = toThousands;